<!doctype html>



  


<html class="theme-next mist use-motion">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>



<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />












  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.4.0" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.0.2" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="algorithm," />








  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.0.2" />






<meta name="description" content="记录一些排序算法">
<meta property="og:type" content="article">
<meta property="og:title" content="排序算法">
<meta property="og:url" content="https://my.oschina.net/u/588736/blog/2016/03/15/common_sort/index.html">
<meta property="og:site_name" content="晚来风">
<meta property="og:description" content="记录一些排序算法">
<meta property="og:image" content="http://7xvh4i.com1.z0.glb.clouddn.com/fifo01.png">
<meta property="og:image" content="http://7xvh4i.com1.z0.glb.clouddn.com/fifo02.png">
<meta property="og:image" content="http://7xvh4i.com1.z0.glb.clouddn.com/fifo03.png">
<meta property="og:image" content="http://7xvh4i.com1.z0.glb.clouddn.com/fifo04.jpg">
<meta property="og:updated_time" content="2016-11-28T09:56:24.939Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="排序算法">
<meta name="twitter:description" content="记录一些排序算法">
<meta name="twitter:image" content="http://7xvh4i.com1.z0.glb.clouddn.com/fifo01.png">



<script type="text/javascript" id="hexo.configuration">
  var NexT = window.NexT || {};
  var CONFIG = {
    scheme: 'Mist',
    sidebar: {"position":"left","display":"always"},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: '0',
      author: '博主'
    }
  };
</script>




  <link rel="canonical" href="https://my.oschina.net/u/588736/blog/2016/03/15/common_sort/"/>


  <title> 排序算法 | 晚来风 </title>
</head>

<body itemscope itemtype="//schema.org/WebPage" lang="zh-Hans">

  










  
  
    
  

  <div class="container one-collumn sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="//schema.org/WPHeader">
      <div class="header-inner"><div class="site-meta ">
  

  <div class="custom-logo-site-title">
    <a href="/"  class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <span class="site-title">晚来风</span>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>
  <p class="site-subtitle">林花谢了春红，太匆匆。</p>
</div>

<div class="site-nav-toggle">
  <button>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
  </button>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-commonweal">
          <a href="/404.html" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-heartbeat"></i> <br />
            
            公益404
          </a>
        </li>
      

      
    </ul>
  

  
</nav>

 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  
  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="//schema.org/Article">

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                排序算法
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            <span class="post-meta-item-icon">
              <i class="fa fa-calendar-o"></i>
            </span>
            <span class="post-meta-item-text">发表于</span>
            <time itemprop="dateCreated" datetime="2016-03-15T00:00:00+08:00" content="2016-03-15">
              2016-03-15
            </time>
          </span>

          
            <span class="post-category" >
              &nbsp; | &nbsp;
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
              
                <span itemprop="about" itemscope itemtype="https://schema.org/Thing">
                  <a href="/categories/简单算法/" itemprop="url" rel="index">
                    <span itemprop="name">简单算法</span>
                  </a>
                </span>

                
                

              
            </span>
          

          
            
          

          

          
          

          
        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>记录一些排序算法</p>
<a id="more"></a>
<h2 id="简单的桶排序"><a href="#简单的桶排序" class="headerlink" title="简单的桶排序"></a>简单的桶排序</h2><p>假如，我们要排序{ 1, 3, 5, 2, 4, 0, 8, 7, 12, 11, 10 }，只需要借助一个一维数组就可以解决：首先申请一个大小为13的一维数组:<br><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">int</span>[] a = <span class="keyword">new</span> <span class="keyword">int</span>[<span class="number">13</span>];</div></pre></td></tr></table></figure></p>
<p>OK。刚开始的时候，将a[0]~a[12]都初始化为0，表示这些数字都没出现，例如a[0]为0表示还没有0出现…，然后开始处理每个元素，第一个为1，则将a[1]加1，表示1出现一次；同理继续处理后面的数字：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">bucket</span><span class="params">(<span class="keyword">int</span>[] a, <span class="keyword">int</span> maxValue)</span> </span>&#123;</div><div class="line">		<span class="keyword">int</span>[] iArr = <span class="keyword">new</span> <span class="keyword">int</span>[maxValue + <span class="number">1</span>];</div><div class="line"></div><div class="line">		<span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; a.length; i++) &#123;</div><div class="line">			iArr[a[i]]++;</div><div class="line">		&#125;</div><div class="line"></div><div class="line">		<span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; iArr.length; i++) &#123;</div><div class="line">			<span class="keyword">for</span> (<span class="keyword">int</span> j = <span class="number">0</span>; j &lt; iArr[i]; j++) &#123;</div><div class="line">				System.out.print(i + <span class="string">" "</span>);</div><div class="line">			&#125;</div><div class="line">		&#125;</div><div class="line">	&#125;</div></pre></td></tr></table></figure></p>
<p>桶的算法时间复杂度为O(M+N)，这是一个非常快的排序算法。当然，真正的桶排序比这复杂的多，桶排序耗费空间，若排序{ 1, 30000, 99999999, … }这种，就得很多的桶，太浪费空间了。</p>
<h2 id="冒泡排序（邻居好说话）"><a href="#冒泡排序（邻居好说话）" class="headerlink" title="冒泡排序（邻居好说话）"></a>冒泡排序（邻居好说话）</h2><p><font face="黑体" color="#0099ff" size="3">冒泡排序的基本思想是：每次相邻两个元素，如果他们的顺序不符合要求，则调换他们的顺序。 </font><br>要排序{ 1, 3, 5, 2, 4, 0, 8, 7, 12, 11, 10 }，说明越小的数越靠前。首先比较前两位，发现1比3小，则不调换顺序；继续比较3和5，不调换；继续比较5和2，调换；以此类推，第一趟下来的结果为：{ 1, 3, 2, 4, 0, 5, 7, 8, 11, 10, 12 }。继续排序：<br>{ 1, 3, 2, 4, 0, 5, 7, 8, 11, 10, 12 }<br>{ 1, 2, 3, 0, 4, 5, 7, 8, 10, 11, 12 }<br>{ 1, 2, 0, 3, 4, 5, 7, 8, 10, 11, 12 }<br>{ 1, 0, 2, 3, 4, 5, 7, 8, 10, 11, 12 }<br>{ 0, 1, 2, 3, 4, 5, 7, 8, 10, 11, 12 }<br>排序完成。 代码：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">bubble</span><span class="params">(<span class="keyword">int</span>[] a)</span> </span>&#123;</div><div class="line">		<span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; a.length; i++) &#123;</div><div class="line">			<span class="keyword">for</span> (<span class="keyword">int</span> j = <span class="number">0</span>; j &lt; a.length - i - <span class="number">1</span>; j++) &#123;</div><div class="line">				<span class="keyword">if</span> (a[j] &gt; a[j + <span class="number">1</span>]) &#123;</div><div class="line">					<span class="keyword">int</span> t = a[j];</div><div class="line">					a[j] = a[j + <span class="number">1</span>];</div><div class="line">					a[j + <span class="number">1</span>] = t;</div><div class="line">				&#125;</div><div class="line">			&#125;</div><div class="line">		&#125;</div><div class="line">	&#125;</div></pre></td></tr></table></figure></p>
<p>冒泡排序的核心是双重嵌套循环，可以看出其时间复杂度是O(N²)，这是一个非常高的时间复杂度。早在1956年就有人研究尝试改进，但是结果却不如人意。正如Donald E. Knuth所说：“冒泡排序除了它迷人的名字和导致了某些有趣的理论问题这一事实<br>之外，似乎没有什么值得推荐的。”</p>
<h2 id="快速排序（最常用）"><a href="#快速排序（最常用）" class="headerlink" title="快速排序（最常用）"></a>快速排序（最常用）</h2><p>我们继续对{ 1, 3, 5, 2, 4, 0, 8, 7, 12, 11, 10 }进行排序，首先在这个序列中找一个<strong>基准数</strong>（即一个参照数），假设为5，然后所有比这个数大的放右边，比这个数小的放左边。初始的时候5在第三个位置，现在就要找到这个位置，并且以该位置为分界点，左边都小于5，右边都大于5。方法很简单：分别从序列的两端开始找，先从右往左找到第一个小于等于5的数字（即0），然后从左往右找到第一个比5大的数字，发现越过了0，即从右向左和从左向右相遇了，说明从左向右“越界”，查找结束，这时候交换0和5（基准数），得到{ 1, 3, 0, 2, 4, 5, 8, 7, 12, 11, 10 }，接着查找，从右向左找“小”数<br>（即5）,和基准数一致，结束。左边{1, 3, 0, 2, 4}，右边{8, 7, 12, 11, 10}，对于这两个子序列继续使用该方法（递归），比如左边{1, 3, 0, 2, 4}:设置基准数为2，从右向左找“小”数（2），从左向右找“大”数（3），交换2和3:{1, 2, 0,  3, 4}，从右向左找“小”数（0）,从左向右找“大”数（3），越界，交换0和基准数2:{1, 0, 2, 3, 4}，OK。  </p>
<p><font face="黑体" color="#0099ff" size="3">快速排序的每一轮处理其实就是将<strong>基准数</strong>归位，直到所有的数都归位为止。</font><br>快速排序之所以比较快，是因为相比冒泡排序，每次交换是跳跃式的。每次排序的时候设置一个基准点，将小于等于基准点的数全部放到基准点的左边，将大于等于基准点的数全部放到基准点的右边。这样在每次交换的时候就不会像冒泡排序一样只能在相邻的数之间进行交换，交换的距离就大得多了。因此总的比较和交换次数就少了，速度自然就提高了。当然在最坏的情况下，仍可能是相邻的两个数进行了交换。因此快速排序的最差时间复杂度和冒泡排序是一样的，都是O(N2)，它的平均时间复杂度为O (NlogN)。其实快速排序是基于一种叫做“二分”的思想。<br><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div></pre></td><td class="code"><pre><div class="line"> <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">quick</span><span class="params">(<span class="keyword">int</span>[] a, <span class="keyword">int</span> iL, <span class="keyword">int</span> iR)</span> </span>&#123;</div><div class="line">	<span class="keyword">if</span> (iL &lt; iR) &#123;</div><div class="line">		<span class="comment">// x为基准数</span></div><div class="line">		<span class="keyword">int</span> i = iL, j = iR, x = a[iL];</div><div class="line"></div><div class="line">		<span class="keyword">while</span> (i &lt; j) &#123;</div><div class="line"></div><div class="line">			<span class="comment">// 从右向左找“小”数</span></div><div class="line">			<span class="keyword">while</span> (i &lt; j &amp;&amp; a[j] &gt;= x)</div><div class="line">				j--;</div><div class="line"></div><div class="line">			<span class="keyword">if</span> (i &lt; j)</div><div class="line">				a[i++] = a[j];</div><div class="line"></div><div class="line">			<span class="comment">// 从左向右找“大”数</span></div><div class="line">			<span class="keyword">while</span> (i &lt; j &amp;&amp; a[i] &lt;= x)</div><div class="line">				i++;</div><div class="line"></div><div class="line">			<span class="keyword">if</span> (i &lt; j)</div><div class="line">				a[j--] = a[i];</div><div class="line">		&#125;</div><div class="line">		a[i] = x;</div><div class="line">		quick(a, iL, i - <span class="number">1</span>);</div><div class="line">		quick(a, i + <span class="number">1</span>, iR);</div><div class="line">	&#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure></p>
<h2 id="LRU-FIFO"><a href="#LRU-FIFO" class="headerlink" title="LRU FIFO"></a>LRU FIFO</h2><p>在一个虚拟存储管理系统中，假如系统分配给一个作业的内存物理块数是3，并且此作业的页面使用顺序为2，3，2，1，5，2，4，5，3，2，5，2，若采用FIFO和LRU置换算法，其产生的缺页次数  </p>
<p>2 3 2 1 5 2 4 5 3 2 5 2</p>
<p>所谓缺页：只要内存中没有，就算缺页，不管是置入还是调入。</p>
<p>当采用FIFO时：  </p>
<p><img src="http://7xvh4i.com1.z0.glb.clouddn.com/fifo01.png" alt="">  </p>
<p><img src="http://7xvh4i.com1.z0.glb.clouddn.com/fifo02.png" alt=""></p>
<p><img src="http://7xvh4i.com1.z0.glb.clouddn.com/fifo03.png" alt=""></p>
<p><img src="http://7xvh4i.com1.z0.glb.clouddn.com/fifo04.jpg" alt=""></p>

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/algorithm/" rel="tag">#algorithm</a>
          
        </div>
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2016/03/11/cpp_virtual_param/" rel="next" title="C++虚函数默认参数问题">
                <i class="fa fa-chevron-left"></i> C++虚函数默认参数问题
              </a>
            
          </div>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2016/03/21/Spring_abc/" rel="prev" title="Spring入门学习">
                Spring入门学习 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel ">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="//schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/images/avatar.gif"
               alt="LenhartG" />
          <p class="site-author-name" itemprop="name">LenhartG</p>
          <p class="site-description motion-element" itemprop="description">美国《时代周刊》2006年度风云人物</p>
        </div>
        <nav class="site-state motion-element">
          <div class="site-state-item site-state-posts">
            <a href="/archives">
              <span class="site-state-item-count">38</span>
              <span class="site-state-item-name">日志</span>
            </a>
          </div>

          
            <div class="site-state-item site-state-categories">
              <a href="/categories">
                <span class="site-state-item-count">14</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            <div class="site-state-item site-state-tags">
              <a href="/tags">
                <span class="site-state-item-count">25</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://github.com/gxjares" target="_blank" title="GitHub">
                  
                    <i class="fa fa-fw fa-github"></i>
                  
                  GitHub
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="http://weibo.com/u/2526255830" target="_blank" title="Weibo">
                  
                    <i class="fa fa-fw fa-weibo"></i>
                  
                  Weibo
                </a>
              </span>
            
          
        </div>

        
        

        
        

      </section>

      
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">
            
              
            
            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#简单的桶排序"><span class="nav-number">1.</span> <span class="nav-text">简单的桶排序</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#冒泡排序（邻居好说话）"><span class="nav-number">2.</span> <span class="nav-text">冒泡排序（邻居好说话）</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#快速排序（最常用）"><span class="nav-number">3.</span> <span class="nav-text">快速排序（最常用）</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#LRU-FIFO"><span class="nav-number">4.</span> <span class="nav-text">LRU FIFO</span></a></li></ol></div>
            
          </div>
        </section>
      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div>
<iframe frameborder="no" border="0" marginwidth="0" marginheight="0" width=330 height=86 src="http://music.163.com/outchain/player?type=2&id=208889&auto=1&height=66"></iframe>
</div>
<div class="copyright" >
  
  &copy;  2015 - 
  <span itemprop="copyrightYear">2017</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">LenhartG</span>
</div>

<!--
<div class="powered-by">
  由 <a class="theme-link" href="https://hexo.io">Hexo</a> 强力驱动
</div>
-->

<!--
<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Mist
  </a>
</div>
-->
        

        
      </div>
    </footer>

    <div class="back-to-top">
      <i class="fa fa-arrow-up"></i>
    </div>
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  



  
  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.0.2"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.0.2"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.0.2"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.0.2"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.0.2"></script>



  



  




  
  

  

  

  

  


</body>
</html>
